Arrays & ObjectsLet's go back to the analogy of computer languages being like regular spoken languages. In English, you have nouns (which you can think of as "things") and verbs (which you can think of as "actions"). Until now, our nouns (data, such as numbers, strings, or variables) and verbs (functions) have been separate.
No longer!
Using objects, we can put our information and the functions that use that information in the same place.
You can also think of objects as combinations of key-value pairs (like arrays), only their keys don't have to be numbers like 0, 1, or 2: they can be strings and variables.
var phonebookEntry = {};
phonebookEntry.name = 'Oxnard Montalvo';
phonebookEntry.number = '(555) 555-5555';
phonebookEntry.phone = function() {
console.log('Calling ' + this.name + ' at ' + this.number + '...');
};
phonebookEntry.phone();
Did you see that? The phonebookEntry
object handled data (a name and a telephone number) as well as a procedure (the function that printed who it was calling).
In that example, we gave the keyname
the value 'Oxnard Montalvo'
and the key number
the value '(555) 555-5555'
. An object is like an array in this way, except its keys can be variables and strings, not just numbers.
Objects are just collections of information (keys and values) between curly braces, like this:
var myObject = {
key: value,
key: value,
key: value
};
Using the above syntax as a guide, create an object, me
, in the editor. It should have a name
key with the value of your name (as a string) and an age
key with the value of your age (as a number).
var me = {
name: "Jesse",
age: 32,
}
Great work! You just created your very first object.
There are two ways to create an object: using object literal notation(which is what you just did) and using the object constructor.
Literal notation is just creating an object with curly braces, like this:
var myObj = {
type: 'fancy',
disposition: 'sunny'
};
var emptyObj = {};
When you use the constructor, the syntax looks like this:
var myObj = new Object();
This tells JavaScript: "I want you to make me a new
thing, and I want that thing to be an Object
.
You can add keys to your object after you've created it in two ways:
myObj["name"] = "Charlie";
myObj.name = "Charlie";
Both are correct, and the second is shorthand for the first. See how this is sort of similar to arrays?
Recreate your me
object in the editor, but this time, use the object constructor. Once you make it, use either the []
notation or the .
notation to give it a name
property with a string value (your name) and anage
property with a number value (your age).
var me = new Object();
me["name"] = "Jesse";
me.age = 32;
Contact ListIn this project, we'll combine our knowledge of objects and arrays to create a simple contact list. Then, using functions, we'll be able to log the entries in our contact list to the console, as well as search for a particular entry.
var friends = {};
friends.bill = {
firstName: "Bill",
lastName: "Gates",
number: "(206) 555-5555",
address: ['One Microsoft Way','Redmond','WA','98052']
};
friends.steve = {
firstName: "Steve",
lastName: "Jobs",
number: "(408) 555-5555",
address: ['1 Infinite Loop','Cupertino','CA','95014']
};
var list = function(obj) {
for(var prop in obj) {
console.log(prop);
}
};
var search = function(name) {
for(var prop in friends) {
if(friends[prop].firstName === name) {
console.log(friends[prop]);
return friends[prop];
}
}
};
list(friends);
search("Steve");
Creating your contact object
First, we need to start with an object to hold our friends.
Create an object called friends
. Feel free to use either object literal notation or the object constructor. Check the Hint if you need a syntax reminder.
Good! Now let's add some friends to our friends
object.
Each friend will need a name, phone number, and so on. We will use a new object for each friend so that we can remember their information! That's right, we'll have objects within objects!
Add a few empty objects to yourfriends
object. Make sure you add a friend named 'bill' and a friend named 'steve'. Use your friends' names as the keys for the empty objects.
var friends = {
bill: {},
steve: {}
}
Next, let's add some properties to our friends. We'll want them to have afirstName
, a lastName
, and anumber
.
Give each of your friends a firstName
,lastName
, and number
. The value for each of these should be a string (check the Hint if you need help). Make surebill
's first name is "Bill"
andsteve
's first name is "Steve"
(again, note the capitalization).
var friends = {
bill: {
firstName: "Bill",
lastName: "Gates",
number: "(504)555-2345"
},
steve: {
firstName: "Steve",
lastName: "Jobs",
number: "(415)882-1093"
}
}
Let's add another property to each of our friends and set it equal to an array. Give each of your friends anaddress
property, and break up their address into an array, like so:
var friends = {
bill: {
firstName: "Bill",
lastName: "Gates",
number: "(504)555-2345",
address: ['One Microsoft Way','Redmond','WA','98052']
},
steve: {
firstName: "Steve",
lastName: "Jobs",
number: "(415)882-1093",
address: ['2101 Waverley St', 'Palo Alto', 'CA', '94301']
}
}
Great work! Now let's add a couple of functions to help us go through our contacts.
The first function we'll create will be called list
, and it will print out all the entries we have in our friends
object. To do this, we'll want to use a bit of new syntax: a for
/in
loop.
It looks like this:
for (var key in object) {
}
The "key" bit can be any placeholder name you like. It's sort of like when you put a placeholder parameter name in a function that takes arguments.
- Create a function
list
that takes a single parameter. - In the body of the function, write a
for
/in
loop. - In the loop, use
console.log
to print out the key. (For example, if you only have bill
and steve
as entries,list
should just print out "bill"
and "steve"
.)
var list = function(obj) {
for(var prop in obj) {
console.log(prop);
}
};
The second function we'll add will be called search
, and it will take a first name as an argument. It will try to match the first name it receives to any of the first names in our friends
contact list. If it finds a match, it will log our friend's contact information (firstName
, lastName
, number
,address
) to the console.
Define a function search
that takes a single argument, name
. If the argument passed to the function matches any of the first names infriends
, it should log that friend's contact information to the consoleand return
it.
var search = function(name) {
for(var prop in friends){
if(friends[prop].firstName == name){
console.log(friends[prop]);
return friends[prop];
}
}
}
Great work! You've created your own list of contacts that you can search through. Try calling both your functions, adding additional friends, changing the fields you include for each friend, and more to customize your new object.
We did some basic logging of your contact list to the console, but we could have made it look even nicer. How might you format the output to look like this?
First Name: Steve
Last Name: Jobs
Number: (408) 555-5555
Address: 1 Infinite Loop
Cupertino, CA 95014
var friends = {
bill: {
firstName: "Bill",
lastName: "Gates",
number: "(504)555-2345",
address: ['One Microsoft Way','Redmond','WA','98052']
},
steve: {
firstName: "Steve",
lastName: "Jobs",
number: "(415)882-1093",
address: ['2101 Waverley St', 'Palo Alto', 'CA', '94301']
}
}
var list = function(obj) {
for(var prop in obj) {
console.log(prop);
}
};
var search = function(name) {
for(var prop in friends){
if(friends[prop].firstName == name){
console.log(friends[prop]);
return friends[prop];
}
}
}